<?php
/**
 * Created by PhpStorm.
 * User: czm
 * Date: 2019-07-17
 * Time: 15:49
 */
namespace app\index\controller;

use think\Controller;
use app\index\model\User;
use think\Db;
use think\Session;

class Login extends Controller
{
    public function login()
    {
        // ->where(['password'=>$password])
        $phone = input('phone');
        $password = MD5(input('password'));
        $User = new User;
        $istrue = User::where(['phone'=>$phone])->find();
        if (!$istrue) {
            $dat = array('code'=>402,'msg'=>'此用户未注册');
            echo json_encode($dat,JSON_FORCE_OBJECT);
        }

        if ($password !== User::where(['phone'=>$phone])->value('password')) {
            $dat = array('code'=>401,'msg'=>'用户名或密码错误');
            echo json_encode($dat,JSON_FORCE_OBJECT);
        } else if ($info = $istrue->visible(['id','phone'])->toArray()) {
            Session::set('phone',$phone);
            session('user',$istrue);
            $sevenday = date('Y-m-d:H:i:s',strtotime("+7 day"));
            $update = User::where('id',$info['id'])->update(['updated_at'=>$sevenday]);
            $dat = array('code'=>200,'msg'=>'登录成功','needinfo'=>$info);
            echo json_encode($dat,JSON_FORCE_OBJECT);
        }

    }

    public function logout()
    {
        $id = input('id');
        if ($id == "error"){
            $dat = ['code' => 403, 'msg' => '登录超时'];
            return json_encode($dat);
        }else{
            $outlogin= User::where('id',$id)->update(['updated_at'=> '']);
            if($outlogin){
                $dat = array('code'=>200,'msg'=>'退出成功');
                echo json_encode($dat,JSON_FORCE_OBJECT);
            }else{
                $dat = array('code'=>200,'msg'=>'退出成功');
                echo json_encode($dat,JSON_FORCE_OBJECT);
            }
        }

    }

}